<%@ page import="com.party.core.model.system.TargetType" %>
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="../include/tag.jsp" %>
<!DOCTYPE html>
<html lang="zh">
<head>
    <title>${epCategory.id == null ? '添加' : '编辑'}分类</title>
    <%@include file="../include/commonFile.jsp" %>
    <link rel="stylesheet" href="${ctx}/css/common/list.css">
    <link rel="stylesheet" href="${ctx}/css/common/img_text.css">
    <link rel="stylesheet" href="${ctx}/static/uploadCI/upload.css">
    <link rel="stylesheet" href="${ctx}/css/ui/activity/publish_form.css">
    <link rel="stylesheet" href="${ctx}/css/ui/mall/goods_form.css">
    <link rel="stylesheet" href="${ctx}/css/form-preview.css">
</head>
<body>
<!--头部-->
<%@include file="../include/header.jsp" %>
<div class="index-outside">
    <%@include file="../include/sidebar.jsp" %>
    <!--内容-->
    <section>
        <div class="section-main">
            <!-- 正文请写在这里 -->
            <div class="add-form-content">
                <form id="myForm" class="layui-form mt20" method="post" action="${ctx}/epService/category/save.do">
                    <input type="hidden" name="id" value="${epCategory.id}"/>
                    <div class="layui-form-item">
                        <div class="layui-form-item">
                            <label class="layui-form-label">分类名称<span class="f-verify-red">*</span></label>
                            <div class="layui-input-block">
                                <input type="text" name="name" id="name" lay-verify="name" autocomplete="off"
                                       class="layui-input" value="${epCategory.name}" maxlength="7"
                                       style="width: 200px; float: left; margin-right: 10px;"
                                >
                                <div class="layui-form-mid layui-word-aux">最多7字符</div>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">排序<span class="f-verify-red">*</span></label>
                            <div class="layui-input-block">
                                <input type="number" name="sort"
                                       class="layui-input" value="${epCategory.sort}"
                                       style="width: 200px;  float: left; margin-right: 10px;" lay-verify="sort">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">显示城市<span class="f-verify-red">*</span></label>
                            <div class="layui-input-block">
                                <input type="hidden" name="categoryList" id="categoryIds" value=""
                                       lay-verify="categoryId"/>
                                <div class="tag-wrap">
                                    <c:forEach var="category" items="${categoryList}">
                                        <div class="tag-item" data-id="${category.id}">
                                            <span class="tag-name">${category.name}</span>
                                            <i class="iconfont icon-close category-opt"></i>
                                        </div>
                                    </c:forEach>
                                </div>
                                <a href="javascript:selectCategory();" class="layui-btn layui-btn-danger addCategoryBtn"
                                   style="float: left; margin-right: 10px;">
                                    <i class="iconfont icon-add btn-icon"></i>
                                    选择城市
                                </a>
                                <div class="layui-form-mid layui-word-aux"><a href="${ctx}/city/list.do" class="red">新增城市</a>
                                </div>
                                <i class="cl"></i>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <div class="layui-input-block">
                                <a href="javascript:void(0)" class="layui-btn layui-btn-danger" lay-submit
                                   lay-filter="*">立即提交</a>
                                <a href="${ctx}/epService/category/list.do"
                                   class="layui-btn layui-btn-primary">取消</a>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
        <%@include file="../include/footer.jsp" %>
    </section>
</div>
<script>
    txz.initHeader({
        nav: [{
            name: '服务分类',
            href: '${ctx}/epService/category/list.do'
        }, {
            name: '${epCategory.id == null ? '添加' : '编辑'}分类',
            curr: true
        }],
        btns: [{
            type: 'back'
        }]
    });

    var form, laydate, formcache;
    $(function () {
        layui.use(['form', 'laydate'], function () {
            form = layui.form, laydate = layui.laydate;

            //自定义验证规则
            form.verify({
                name: function (value) {
                    if (value.trim() == "") {
                        return '分类名不能为空';
                    } else {
                        var isRepeat =false;
                        $.ajax({
                            type: 'POST',
                            async: false, // 使用同步的方法
                            data: {
                                name: $("#name").val(),
                                id: '${epCategory.id}'
                            },
                            dataType: 'json',
                            success: function (data) {
                                isRepeat = data.success;
                            },
                            url: '${ctx}/epService/category/verifyName.do'
                        });

                        if(!isRepeat){
                            return '分类名已存在';
                        }
                    }
                },
                sort: function (value) {
                    if (value.trim() == "") {
                        return "请填写序号";
                    }
                    if (value <= 0) {
                        return "请填写正确的序号";
                    }

                },
                categoryId: function (value) {
                    var length = $(".tag-item").length;
                    if (length == 0) {
                        return "请选择城市";
                    }
                }
            });


            //监听提交
            form.on('submit', function (data) {
                submitForm(data);
                localStorage.removeItem("server_myCategory");
            });

        });

        $(".tag-wrap").delegate(".category-opt", "click", function (e) {
            var target = $(e.target);
            var value = $(target).closest(".tag-item").data("id");
            $(target).closest(".tag-item").remove();

            var giftJson = localStorage.getItem("server_myCategory");
            var _giftArray = eval(giftJson);

            var index = -1; // 如果不存在返回-1，否则返回index
            $.each(_giftArray, function (ii, dd) {
                if (value == dd.id) {
                    index = ii;
                }
            });
            _giftArray.splice(index, 1);
            localStorage.setItem("server_myCategory", JSON.stringify(_giftArray));
        })
    });


    function submitForm(data) {
        txz.submitObject(data.elem, function (callBack) {

            var formData = getFormData();
            var action = $("#myForm").attr("action");
            txz.ajaxRequest({
                method: 'post',
                url: action,
                saveCache: true,
                cacheObj: formcache,
                params: formData,
                callBack: function (res) {
                    typeof callBack === 'function' && callBack();
                    if (res.success) {
                        util.layerMsgSuccess("提交成功", function () {
                            location.href = "${ctx}/epService/category/list.do";
                        });
                    } else {
                        util.layerMsgError("提交失败")
                    }
                }
            });
        })
    }

    function getFormData() {


        // 分类
        var _giftArray = new Array();
        var _categoryArray = new Array();
        $(".tag-wrap .tag-item").each(function (index, elem) {
            var tagId = $(elem).data("id");
            var tagName = $(elem).find(".tag-name").text();
            _giftArray.push(tagId);
            var map = {
                id: tagId,
                name: tagName
            };
            _categoryArray.push(map);
        });
        if (_giftArray.length > 0) {
            $("#categoryIds").val(_giftArray.join(","));
            $("[name=categoryCache]").val(JSON.stringify(_categoryArray));
        }

        return util.serializeForm($('#myForm').serializeArray());
    }

    function delQImg(obj) {
        $(obj).closest(".item").remove();
        var imgLength = $("#img_list .item").length;
        if (imgLength < maxNum) {
            $(".addPicBtn").prop('disabled', false);
        }
    }


    function selectCategory() {
        function cb($jquery) {
            var categoryIds = $($jquery.find("#categoryIds")).val();
            var categoryNames = $($jquery.find("#categoryNames")).val();
            var _idsArray = categoryIds.split(",");
            var _namesArray = categoryNames.split(",");
            var _contentArray = new Array();
            for (var i = 0; i < _idsArray.length; i++) {
                _contentArray.push('<div class="tag-item" data-id="' + _idsArray[i] + '">');
                _contentArray.push('<span class="tag-name">' + _namesArray[i] + '</span>');
                _contentArray.push('<i class="iconfont icon-close category-opt"></i>');
                _contentArray.push('</div>');
            }
            var $content = $(".tag-wrap");
            $content.html(_contentArray.join(""));

        }

        var _giftArray = new Array();
        $(".tag-wrap .tag-item").each(function (index, elem) {
            var giftId = $(elem).data("id");
            _giftArray.push(giftId);
        });
        var categoryIds = _giftArray.join(",");
        openDialog('选择城市', '${ctx}/city/cityInfo.do?categoryIds=' + categoryIds, '450px', '600px', cb);
    }

    function openDialog(title, url, width, height, cb, target) {
        layer.open({
            type: 2,
            area: [width, height],
            title: title,
            maxmin: true, //开启最大化最小化按钮
            content: url,
            btn: ['确定', '关闭'],
            yes: function (index, layero) {
                var body = layer.getChildFrame('body', index);
                var iframeWin = layero.find('iframe')[0]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                var inputForm = body.find('#inputForm');
                var top_iframe;
                if (target) {
                    top_iframe = target;//如果指定了iframe，则在改frame中跳转
                } else {
                    top_iframe = '_parent';//获取当前active的tab的iframe
                }
                inputForm.attr("target", top_iframe);//表单提交成功后，从服务器返回的url在当前tab中展示

                if (iframeWin.contentWindow.doSubmit()) {
                    cb(iframeWin.contentWindow.$);

                    setTimeout(function () {
                        top.layer.close(index);
                    }, 100);//延时0.1秒，对应360 7.1版本bug
                }

            },
            cancel: function (index) {
            }
        });
    }
</script>
</body>
</html>